﻿/**当前文件路径指针*/
var currentPath;
	$(document).ready(function() {
		getFiles("\\");
		countPercent();
		//全选
		$("#checkAll").click(function () {
				$("input[name='check_name']").prop("checked", $(this).prop("checked"));
				if($(this).prop("checked")){
					$("#operation").show();
				}else{
					$("#operation").hide()
				}
		});
		//显示隐藏操作栏
		$("#operation").hide()
	});
	function selectCheckbox(){
		$inputs = $("input[name='check_name']");
		var len = $inputs.filter(":checked").length;
		$("#checkAll").prop("checked", len == $inputs.length);
		$("#operation").show();
		if(len == 0){
			$("#operation").hide();
		}
	}
	/**计算容量百分比*/
	function countPercent(){
		var countSize = $("#countSize").text();
		var totalSize = $("#totalSize").text();
		var countSizeNum = parseFloat(countSize.substr(0, countSize.length - 2));
		var totalSizeNum = parseFloat(totalSize.substr(0, totalSize.length - 2));
		totalSizeNum *= (1024 * 1024 * 1024);
		if(!isNaN(countSizeNum)){
			var unit = countSize.substr(countSize.length - 2);
			if(unit == "KB"){
				countSizeNum *= 1024;
			}else if(unit == "MB"){
				countSizeNum *= (1024 * 1024);
			}else if(unit == "GB"){
				countSizeNum *= (1024 * 1024 * 1024);
			}
		}else{
			countSizeNum = 0;
		}
		var percent = Math.round(countSizeNum * 100 / totalSizeNum) + "%";
		$("#sizeprogress").css("width", percent).attr("aria-valuemax", totalSizeNum).text(percent);
	}
	/**文件路径导航点击事件*/
	function theClick(obj) {
		getFiles($(obj).attr("path"));
		$(obj).nextAll().remove();
		return false;
	}
	/**导航栏添加导航项*/
	function navPath(path, currentPath) {
		$("#navPath").append(
				'<a href="#" path="' + path
						+ '" onclick="return theClick(this)">&nbsp;'
						+ currentPath + '&nbsp;&#62;</a>');
	}
	/**上传文件点击事件*/
	function upload(obj) {
		$("#input_file").click();
		return false;
	}

	/**上传文件*upload()*/
	function upload(){
		var files = document.getElementById("input").files;
		       
		if(files.length==0) {  
		    alert("请选择文件");  
		    return;  
		}
	    var index = layer.load(1, {
		  shade: [0.75,'#fff'] //0.1透明度的白色背景
		});
	    //我们可以预先定义一个FormData对象  
	    var formData=new FormData();  
	    for(var i=0;i<files.length;i++) {  
	        //将每个文件设置一个string类型的名字，放入到formData中，这里类似于setAttribute("",Object)  
	        formData.append("files",files[i]);  
	    }
	    formData.append("currentPath", currentPath);
	    $.ajax({     
			url: 'file/upload.action',  
			type: 'POST',  
			cache: false,
			//这个参数是jquery特有的，不进行序列化，因为我们不是json格式的字符串，而是要传文件  
			processData: false,  
			//注意这里一定要设置contentType:false，不然会默认为传的是字符串，这样文件就传不过去了  
			contentType: false,  
			data : formData,
			success : function(data) {
				if (data.success == true) {
					getFiles(currentPath);
					layer.closeAll('loading');
				}
			},
	    });  
	}
	/**
	多文件下载选择下载
	*/
	function downloadFileSelect(obj){
		var $download = $("input:checked");
		var downPath = "";
		$.each($download.parent().next().children(),function(i,n){
			downPath += "&downPath=" + $(this).text();
		});
		if($download.length <= 0){
			alert("必须选择一个");
			$download.removeAttr("checked");
		}else{
			return download(obj, downPath);
		}
	}
	/**
	 * 单文件下载按钮下载
	 */
	function downloadFile(obj){
		$file = $(obj).parent().prev().prev().children();
		var path = $file.attr("path");
		if(path==null){
			path = $file.text();
		}
		return download(obj, "&downPath="+ encodeURI(path));
	}
	/**
	 * 下载
	 */
	function download(obj, path){
		var url = "file/download.action?";
		url += ("currentPath=" + encodeURI(currentPath));
		url += path;
		$(obj).attr("href", url);
		return true;
	}
	/**
	重命名文件名 
	 */
	function rename() {
        var obj = document.getElementsByName('isSelect');
        var id;
        for (var i = 0; i < obj.length; i++) {
            if (obj[i].checked) {
                id=obj[i].value;//如果选中，将value添加到变量s中
                layer.prompt({title: '重命名'}, function(destName, index){
                    if(destName.trim() == ""){
                        layer.close(index);
                        layer.msg('名字不合法，修改失败！');
                    }else{
                        $.post("../files/renameFile",{
                            "id":id,
                            "name":destName
                        },function(data){
                            if(data=="success"){
                                layer.msg('重命名成功');
                                layer.close(index);
                                window.location.reload();
                            }
                        });
                    }
                });
            }
        }
		return false;
	}

	/**
	 删除文件 */
        function deleteall() {
        var obj = document.getElementsByName('isSelect');
        var s1 = "Select:";
        var ids = "";
        for (var i = 0; i < obj.length; i++) {
            if (obj[i].checked) {
                ids += obj[i].value + ","; //如果选中，将value添加到变量s中
                //alert(obj[i].value)
            }
        }
        if (ids == '') {
            alert("请先选择要删除的文件");
        }
        else {
            layer.msg("你确定删除吗？（删除后可在回收站中找回）", {
                time: 0
                , btn: ['确定', '取消']
                , yes: function () {
                    $.get("../files/FalseDel?ids=" + ids, function (data) {
                        if ("success" == data) {
                            layer.msg('已删除', {time:200000,icon: 1});
                            window.location.reload();
                        }
                        else {
                            alert("Error!");
                        }
                    });
                }
            });
        }
    }

    //新建文件夹
    function buildfile(){
		layer.prompt({title: '新建文件夹'}, function(filename, index){
			var id = getQueryString("folderId");
			  $.post("../files/addDirectory",{
				  "directoryName":filename,
				  "directoryId":id
			  },function(data){
				  layer.msg('新建文件夹'+filename+'成功');
				  layer.close(index);
				  window.location.reload();
			  });
		});
		return false;
	}
/**分享文件*/
function share() {
    var obj = document.getElementsByName('isSelect');
    var s1 = "Select:";
    var ids = "";
    for (var i = 0; i < obj.length; i++) {
        if (obj[i].checked) {
            ids += obj[i].value + ","; //如果选中，将value添加到变量s中
        }
    }
    if (ids == '') {
        alert("请先选择要分享的文件");
    }
    else {
        layer.msg("你确定分享吗？（分享后可在我的分享中查看）", {
            time: 0
            , btn: ['确定', '取消']
        }, function () {
            $.get("../shares/addShare?ids=" + ids,
                function (data) {
                    if ("success" == data) {
                        layer.msg('分享成功', {icon: 1});
                        window.location.reload();
                    }
                    else {
                        alert("Error!");
                    }
                });
        }, function () {
            layer.msg('已取消', {
                time: 2000, //2s后自动关闭
            });
        });
    }
    return false;
}
	/**打开我的分享*/
	function openMyShare(){
		layer.open({ 
			  type: 1, 
			  area: ['850px', '450px'],
			  title:false,
			  content: $("#shareTab")
			});
	}
	/**查找文件*/
	function searchFileType(type){
		var tabName = type + "Tab";
		$("#fileTypeList li").has("a[aria-controls='"+tabName+"']").addClass("active").siblings().removeClass("active");
		$("#"+tabName).addClass("active").siblings().removeClass("active");
		changeTypeTab(type);
		layer.open({ 
			  type: 1, 
			  zIndex : 80,
			  area: ['890px', '450px'],
			  title:false,
			  content: $("#fileTypeList")
			});
		return false;
	}
	/**切换文件类型*/
	function changeTypeTab(type){
		/*$.post("file/searchFile.action", {
			"regType" : type
		}, function(data) {
			if (data.success) {
				var typeName = type+"Tab";
				if(type == "image"){
					$("#"+ typeName).empty();
					$.each(data.data, function() {
						var url = encodeURI('currentPath='+this.currentPath+'&fileType='+this.fileType+'&fileName='+this.fileName);
						$("#"+ typeName).append('<a href="file/openFile.action?'+url+'" data-lightbox="roadtrip" title="'+this.fileName+'"><img alt="'+this.fileName+'" style="margin: 10px" src="file/openFile.action?'+url+'" width="150" height="150"></a>')
					});
				}else{
					$("#"+ typeName + " tbody").empty();
					$.each(data.data, function() {
						$("#"+ typeName + " tbody").append('<tr><td><a href="#" onclick="return openFile(this)" filetype="'+this.fileType+'" currentPath="'+this.currentPath+'"><span class="glyphicon glyphicon-'+this.fileType+'" style="margin-right: 10px"></span>'+this.fileName+'</a></td><td>'+this.fileSize+'</td><td>'+this.lastTime+'</td></tr>');
					});
				}
			}
		});
		return false;*/
	}
	/**分类型打开文件*/
	function openFile(obj) {
		/*var fileType = $(obj).attr("filetype")
		var fileName = $(obj).text();
		var parentPath = $(obj).attr("currentPath") == null ? currentPath : $(obj).attr("currentPath");
		var url = encodeURI('currentPath='+parentPath+'&fileType='+fileType+'&fileName='+fileName);
		alert(url);
		if (fileType == "folder-open") {
			var prePath = $(obj).attr("prePath");
			var path = prePath + "\\" + fileName;
			getFiles(path);
			navPath(path, fileName); 
		} else if(fileType.indexOf("image") >= 0){
			$(obj).attr({"href":"file/openFile.action?"+url,"data-lightbox":"test","data-title":fileName});
			return true;
		} else if(fileType.indexOf("office") >= 0){
			$.post("file/openOffice.action", {
				"currentPath" : parentPath,
				"fileType" : fileType,
				"fileName" : fileName,
			}, function(data){
				if(data.success){
					openOffice(data.data);
				}else{
					layer.msg(data.msg);
				}
			});
		} else if(fileType.indexOf("audio") >= 0){
			layer.open({
				type:2,
				title:'播放',
				content:'file/openAudioPage.action?' + url,
				shade: [0],
				area: ['440px', '120px'],
				offset: 'rb', //右下角弹出
			});
		} else if(fileType.indexOf("docum") >= 0){
			$.post("file/openFile.action", {
				"currentPath" : parentPath,
				"fileType" : fileType,
				"fileName" : fileName,
			}, function(data){
				layer.open({ 
					  type: 1, 
					  area: ['720px', '570px'],
					  title:false,
					  scrollbar: false,
					  content: '<textarea rows="50" cols="150">'+data+'</textarea>'
					});
			});
		} else if(fileType.indexOf("vido") >= 0){
			layer.open({ 
				  type: 1, 
				  area: ['480px', '400px'],
				  title:false,
				  content: '<div id="a1"></div>'
				});
			var flashvars={
			        f:'file/openFile.action?' + url,
//					f:'http://movie.ks.js.cn/flv/other/1_0.flv',
			        c:0,
			        p:1,
			        b:1
		    };
		    var params={bgcolor:'#FFF',allowFullScreen:true,allowScriptAccess:'always',wmode:'transparent'};
		    CKobject.embedSWF('js/ckplayer/ckplayer.swf','a1','ckplayer_a1','480','400',flashvars,params);
		    return false;
		}
		return false;*/
	}
	
	function openOffice(id){
	/*	layer.open({
			  type: 1, 
			  zIndex : 80,
			  area: ['auto','600px'],
			  offset: '10px',
			  title:false,
			  content: '<div id="officeContent"></div>'
			});
		    var option = {
		        docId: id,
		        token: 'TOKEN',
		        host: 'BCEDOC',
		        serverHost: 'http://doc.bj.baidubce.com',
		        width: 600, //文档容器宽度
//		        zoom: false,              //是否显示放大缩小按钮
		        ready: function (handler) {  // 设置字体大小和颜色, 背景颜色（可设置白天黑夜模式）
		            handler.setFontSize(1);
		            handler.setBackgroundColor('#000');
		            handler.setFontColor('#fff');
		        },
		        flip: function (data) {    // 翻页时回调函数, 可供客户进行统计等
		            console.log(data.pn);
		        },
		        fontSize:'big',
		        toolbarConf: {
		                zoom: false,
		        		page: false, //上下翻页箭头图标
		                pagenum: false, //几分之几页
		                full: false, //是否显示全屏图标,点击后全屏
		                copy: true, //是否可以复制文档内容
		                position: 'center',// 设置 toolbar中翻页和放大图标的位置(值有left/center)
		        } //文档顶部工具条配置对象,必选
		    };
		    new Document('officeContent', option);*/
	}
